﻿using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;
using Newtonsoft.Json;
using QDCommon.Controller;
using System.Collections.Concurrent;
namespace QDCommon.SignalR
{
    public class QDHub : Hub
    {
        static ConcurrentDictionary<string, string> userDic = new ConcurrentDictionary<string, string>();
        public QDHub():base()
        { 
        }
        public override Task OnConnectedAsync()
        {
            userDic[Sender()] = Context.ConnectionId;
            return base.OnConnectedAsync();
 
        }

        public override Task OnDisconnectedAsync(Exception exception)
        {
            return base.OnDisconnectedAsync(exception);
        }

        public async Task SendMessage(string to, string actionName, string message)
        {
            string clientId = userDic[to];
            var client = Clients.Client(clientId);
            if (client != null)
            {
                await client.SendAsync(actionName, Sender(), message);

            }
            else
            {

            }
        }

        #region
        public async Task JoninGroup(string groupName)
        {
            await Groups.AddToGroupAsync(this.Context.ConnectionId, groupName);
        }

        public async Task RemoveFromGroup(string groupName)
        {
            await Groups.RemoveFromGroupAsync(Context.ConnectionId, groupName);
        }

        public async Task SendMessageToGroup(string groupName,string actionName,string message)
        {
            await Clients.Group(groupName)?.SendAsync(actionName, Sender(), message);
        }
        public async Task SendMessageToGroupWithOutSelf(string groupName,string actionName,string message)
        {
            await Clients.OthersInGroup(groupName).SendAsync(actionName, Sender(), message);
        }
#endregion

        private string Sender()
        {
            return UserIdentityHelper.GetUserName(Context.User);
        }
    }
}
